#include<stdio.h>
#include<gmp.h>
#include<pthread.h>

mpf_t a, a_old, b , b_old, t, t_old ,p , pi, pi_old;

void *calc_a(void *args){
    mpf_add(a, a_old, b_old);
    mpf_div_ui(a , a , 2);
}

void *calc_b(void *args){
    mpf_mul(b, a_old, b_old);
    mpf_sqrt(b,b);
}

void *calc_t(void *args){
    mpf_sub(t, a_old , a);
    mpf_pow_ui(t, t , 2);
    mpf_mul(t, t, p);
    mpf_sub(t, t_old, t);
}

void *calc_p(void *args){
    mpf_mul_ui(p , p, 2);
}

int main (void)
{

    int i;
    pthread_t thread_a, thread_b, thread_t, thread_p;

    mpf_set_default_prec(34000000);

    mpf_inits(a, b, t, p, NULL);
    mpf_init_set_ui(a_old, 1);

    mpf_init_set_ui(pi,0);
    mpf_init_set_ui(pi_old,1);

    mpf_init_set_ui(b_old, 2);
    mpf_sqrt(b_old,b_old);
    mpf_ui_div(b_old, 1 , b_old);


    mpf_init_set_d(t_old, 0.25);

    mpf_init_set_ui(p, 1);

    for(i=0 ; i< 100 ; i++)
    {
        mpf_set(pi_old, pi);

        pthread_create(&thread_a, NULL, calc_a, NULL);
        pthread_create(&thread_b, NULL, calc_b, NULL);
        pthread_create(&thread_p, NULL, calc_p, NULL);
        pthread_join(thread_a, NULL);
        pthread_create(&thread_t, NULL, calc_t, NULL);

        pthread_join(thread_b, NULL);
        pthread_join(thread_t, NULL);
        mpf_set(a_old, a);
        mpf_set(b_old, b);
        mpf_set(t_old, t);
    }

    mpf_add(pi, a, b);
    mpf_mul(pi, pi, pi);
    mpf_mul_ui(t, t , 4);

    mpf_div(pi, pi, t);

    gmp_printf("Iteracoes: %d  %.10000000Ff\n\n", i, pi);

    mpf_clear(a);
    mpf_clear(a_old);
    mpf_clear(b);
    mpf_clear(b_old);
    mpf_clear(t);
    mpf_clear(t_old);
    mpf_clear(p);
    mpf_clear(pi);
    mpf_clear(pi_old);

    return 0;
}

